package top.wuyang.study.java24.servlet.softwaretype;

import top.wuyang.study.java24.dao.TbSoftwareDAO;
import top.wuyang.study.java24.dao.TbSoftwareTypeDAO;
import top.wuyang.study.java24.entity.Result;
import top.wuyang.study.java24.entity.TbSoftwareType;
import top.wuyang.study.java24.util.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "softwareTypeDeleteLinkServlet", urlPatterns = "/softwaretype/deletelink.action")
public class DeleteLinkServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        resp.setContentType("application/json");
        // 删除分类和分类中的软件
        try {
            Integer id = Integer.parseInt(req.getParameter("id"));
            TbSoftwareType softwareType = TbSoftwareTypeDAO.queryById(id);
            if (softwareType==null){
                Result<String> result = Result.success("删除成功",null);
                writer.println(JsonUtils.stringify(result));
                return;
            }
            // 删除分类中的所有员工
            int softwares = TbSoftwareDAO.deleteByTypeId(id);
            System.out.println("删除的软件数" + softwares);
            // 再删除分类
            int count = TbSoftwareTypeDAO.delete(id);
            if (count == 1) {
                Result<String> result = Result.success("删除成功");
                writer.println(JsonUtils.stringify(result));
            } else {
                Result<String> result = Result.fail("删除失败", null);
                writer.println(JsonUtils.stringify(result));
            }


        } catch (Exception e) {
            e.printStackTrace();
            Result<String> result = Result.fail("添加发生错误", null);
            writer.println(JsonUtils.stringify(result));
        }
    }


}
